package com.javaee.my.user;

import com.javaee.interceptor.Utils.SqlSessionFactoryUtils;
import com.javaee.interceptor.Utils.loginCookies;
import com.javaee.interceptor.entity.user;
import org.apache.commons.lang.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

/**
 * 登录servlet
 */

@WebServlet("/login")
public class HelloController extends HttpServlet implements BaseControllerApi{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置返回的头信息
        //当勾选记住的时候，判断是否有cookie，决定创建cookie，最后转发到index.jsp当中
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        user entityuser = new user(0,username,password);
        Integer res=sqlsession.selectOne("com.javaee.my.dao.userMapper.queryByUserNameAndPassword",
                entityuser);//查询数据库是否有这个人
        if (StringUtils.isBlank(String.valueOf(res)))
        {
            System.out.println("校验失败，请重新登陆！");
            req.getRequestDispatcher("404.jsp").forward(req,resp);
            return;
        }else
        {
            System.out.println("校验成功！");
            loginCookies.login(req,resp);
            session.setAttribute("username",username);
            session.setAttribute("password",password);
            session.setAttribute("id",res);//保存用户的唯一标识，id
            req.getRequestDispatcher("display.jsp").forward(req,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
